import { defineStore } from 'pinia'
import * as authApi from '@/api/auth'
import type { User as ApiUser } from '@/api/auth'

interface User {
  id: string
  username: string
  email: string
  fullName: string
  avatar?: string
  role: string
  department?: string
  isActive: boolean
}

interface AuthState {
  user: User | null
  token: string | null
  refreshToken: string | null
  isAuthenticated: boolean
  isLoading: boolean
  error: string | null
}

export const useAuthStore = defineStore('auth', {
  state: (): AuthState => ({
    user: null,
    token: null,
    refreshToken: null,
    isAuthenticated: false,
    isLoading: false,
    error: null
  }),

  actions: {
    async login(email: string, password: string) {
      this.isLoading = true
      this.error = null

      try {
        // Call real API
        const response = await authApi.login({ email, password })

        // Backend returns { success: true, data: { user, accessToken, refreshToken } }
        const { user, accessToken, refreshToken } = response.data

        // Transform API user to store user format
        this.user = {
          id: user._id,
          username: user.username,
          email: user.email,
          fullName: user.fullName || user.username,
          avatar: user.avatar,
          role: user.role,
          isActive: user.status === 'active',
        }

        this.token = accessToken
        this.refreshToken = refreshToken
        this.isAuthenticated = true

        // Save token to localStorage for persistence
        localStorage.setItem('accessToken', accessToken)
        localStorage.setItem('refreshToken', refreshToken)

        this.isLoading = false
      } catch (error: any) {
        this.isLoading = false
        this.error = error.response?.data?.error || error.message || 'Login failed'
        throw error
      }
    },

    async logout() {
      try {
        // Call logout API
        if (this.token) {
          await authApi.logout()
        }
      } catch (error) {
        console.error('Logout API error:', error)
      } finally {
        // Clear state
        this.user = null
        this.token = null
        this.refreshToken = null
        this.isAuthenticated = false
        this.error = null

        // Clear localStorage
        localStorage.removeItem('accessToken')
        localStorage.removeItem('refreshToken')
        localStorage.removeItem('pinia-auth')
      }
    },

    async fetchCurrentUser() {
      if (!this.token) {
        throw new Error('No token available')
      }

      try {
        const response = await authApi.getCurrentUser()
        // Backend returns { success: true, data: user }
        const user = response.data

        this.user = {
          id: user._id,
          username: user.username,
          email: user.email,
          fullName: user.fullName || user.username,
          avatar: user.avatar,
          role: user.role,
          isActive: user.status === 'active',
        }
        this.isAuthenticated = true
      } catch (error: any) {
        console.error('Failed to fetch current user:', error)
        // If token is invalid, clear auth state
        if (error.response?.status === 401) {
          this.logout()
        }
        throw error
      }
    },

    async refreshAccessToken() {
      if (!this.refreshToken) {
        throw new Error('No refresh token available')
      }

      try {
        const response = await authApi.refreshToken(this.refreshToken)
        // Backend returns { success: true, data: { accessToken } }
        const { accessToken } = response.data

        this.token = accessToken
        localStorage.setItem('accessToken', accessToken)
      } catch (error) {
        console.error('Failed to refresh token:', error)
        this.logout()
        throw error
      }
    },

    async updateProfile(updates: Partial<ApiUser>) {
      // TODO: Implement updateProfile API
      console.warn('updateProfile not implemented yet')
      throw new Error('Not implemented')
    },

    async changePassword(oldPassword: string, newPassword: string) {
      // TODO: Implement changePassword API
      console.warn('changePassword not implemented yet')
      throw new Error('Not implemented')
    },

    // Initialize auth from localStorage
    initializeAuth() {
      const accessToken = localStorage.getItem('accessToken')
      const refreshToken = localStorage.getItem('refreshToken')

      if (accessToken && refreshToken) {
        this.token = accessToken
        this.refreshToken = refreshToken
        // Fetch current user to validate token
        this.fetchCurrentUser().catch(() => {
          // Token invalid, clear everything
          this.logout()
        })
      }
    },

    checkPermission(resource: string, action: string): boolean {
      if (!this.user) return false

      // Admin has all permissions
      if (this.user.role === 'admin') {
        return true
      }

      // Ops can read/write alerts and tickets
      if (this.user.role === 'ops') {
        if (resource === 'alerts' || resource === 'tickets') {
          return true
        }
      }

      // Viewer can only read
      if (this.user.role === 'viewer') {
        if (action === 'read') {
          return true
        }
      }

      return false
    },

    setLoading(loading: boolean) {
      this.isLoading = loading
    },

    setError(error: string | null) {
      this.error = error
    },

    clearError() {
      this.error = null
    }
  }
})
